package com.luoran.bartalks.action;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.luoran.bartalks.action.vo.MaterialMoveVo;
import com.luoran.bartalks.action.vo.PlanImplementationVo;
import com.luoran.bartalks.core.UserContext;
import com.luoran.bartalks.entity.biz.BtOperationLog;
import com.luoran.bartalks.entity.biz.BtPlanBiz;
import com.luoran.bartalks.entity.biz.BtPlanDetails;
import com.luoran.bartalks.entity.biz.BtPlanEntry;
import com.luoran.bartalks.entity.biz.BtProject;
import com.luoran.bartalks.entity.biz.BtProjectMember;
import com.luoran.bartalks.entity.biz.BtRuleRecord;
import com.luoran.bartalks.service.IWorkbenchService;
import com.luoran.bartalks.utils.EnumOperationType;

/**
 * 工作台
 * 
 * @author wmm 2018年4月10日 下午6:24:23
 */
@Controller
@RequestMapping("/workbench")
public class WorkbenchAction {
	private static final Logger log = LoggerFactory.getLogger(WorkbenchAction.class);
	SimpleDateFormat myDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	SimpleDateFormat myDateFormat = new SimpleDateFormat("yyyy-MM-dd");
	@Autowired
	private IWorkbenchService service;

	@RequestMapping
	public String success() {
		log.info("跳转工作台页面");
		return "/biz/home";
	}

	/**
	 * 获取项目信息
	 * 
	 * @param number
	 * @return
	 */
	@RequestMapping("/project/{number}")
	@ResponseBody
	public JSONObject getProjectInfo(@PathVariable String number) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		// 0:已启动,1未启动
		List<BtProject> projects = service.queryProjectByCompanyIdOfWorkbench(UserContext.get().getCompanyId(),
				startRow, 0);
		if (projects != null && projects.size() != 0) {
			for (BtProject btProject : projects) {
				// 人员类型(0.管理员,1.成员)
				List<BtProjectMember> members = service.getProjectMemberByProjectIdAndMembertype(btProject.getId(), 0);
				String managerName = "";
				for (int i = 0; i < members.size(); i++) {
					if (i == members.size() - 1) {
						managerName = managerName + members.get(i).getMemberName();
					} else {
						managerName = managerName + members.get(i).getMemberName() + " , ";
					}
				}
				btProject.setManagerName(managerName);
				btProject.setCreateDateStr(myDateTimeFormat.format(btProject.getCreateDate()));
			}
			result.put("state", true);
			result.put("list", projects);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 获取用户操作信息
	 * 
	 * @param number
	 * @return
	 */
	@RequestMapping("/log/{number}")
	@ResponseBody
	public JSONObject getOperationLogInfo(@PathVariable String number) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<BtOperationLog> operationLogs = service.queryUserlogByCompanyId(UserContext.get().getCompanyId(),
				startRow);
		if (operationLogs != null && operationLogs.size() != 0) {
			for (BtOperationLog btOperationLog : operationLogs) {
				btOperationLog.setOperationTypeStr(EnumOperationType.getValueByName(btOperationLog.getOperationType()));
				btOperationLog.setOperateDateStr(myDateTimeFormat.format(btOperationLog.getOperateDate()));
			}
			result.put("state", true);
			result.put("list", operationLogs);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 获取计划信息
	 * 
	 * @param projectid
	 * @return
	 */
	@RequestMapping("/plan/{number}")
	@ResponseBody
	public JSONObject getPlanInfo(@PathVariable String number,
			@RequestParam(value = "projectId", required = false) String projectId) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<PlanImplementationVo> planImplementationList = new ArrayList<>();
		List<BtPlanDetails> planDetails = service.queryPlanByProjectIdOfWorkbench(projectId, startRow);
		if (planDetails != null && planDetails.size() != 0) {
			for (BtPlanDetails btPlanDetails : planDetails) {
				PlanImplementationVo planImplementation = new PlanImplementationVo();
				planImplementation.setPlanId(btPlanDetails.getId());
				planImplementation.setPlanCode(btPlanDetails.getPlanCode());
				planImplementation.setRemark(btPlanDetails.getRemark());
				planImplementation.setStartDateStr(myDateFormat.format(btPlanDetails.getStartDate()));
				planImplementation.setEndDateStr(myDateFormat.format(btPlanDetails.getEndDate()));
				if (btPlanDetails.getStatus() == 4) {
					planImplementation.setHasException(1);
				} else {
					planImplementation.setHasException(0);
				}
				List<BtPlanEntry> planEntrys = service.getPlanEntryByPlanIdOfWorkbench(btPlanDetails.getId());
				// 如果此地点有装卸货业务则为到达该地点,如果此地点的装卸货容器有运输容器则视为已经出发
				if (planEntrys != null && planEntrys.size() != 0) {
					for (BtPlanEntry btPlanEntry : planEntrys) {
						List<BtPlanBiz> findArrive = service.findArrive(btPlanDetails.getProjectId(),
								btPlanDetails.getId(), btPlanEntry.getId());
						if (findArrive != null && findArrive.size() != 0) {
							for (BtPlanBiz btPlanBiz : findArrive) {
								if (service.findContainerTypeById(btPlanBiz.getContainerId()).getContainerType() != 1) {
									btPlanEntry.setArrive(1);
									break;
								} else {
									btPlanEntry.setArrive(2);
								}
							}
						} else {
							btPlanEntry.setArrive(0);
						}
					}
					planImplementation.setPlanEntry(planEntrys);
				} else {
					planImplementation.setPlanEntry(null);
				}
				planImplementationList.add(planImplementation);
			}
			result.put("state", true);
			result.put("obj", planImplementationList);
		} else {
			result.put("state", true);
			result.put("obj", null);
		}
		return result;
	}

	/**
	 * 获取货物移动信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/material/{number}")
	@ResponseBody
	public JSONObject getMaterialMoveInfo(@PathVariable String number,
			@RequestParam(value = "projectId", required = false) String projectId) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<MaterialMoveVo> materialMoves = service.queryMaterialMoveByProjectId(projectId, startRow);
		if (materialMoves != null && materialMoves.size() != 0) {
			for (MaterialMoveVo materialMoveVO : materialMoves) {
				if (materialMoveVO.getBizType() == 10) {
					materialMoveVO.setOperationRecord("装货");
				} else if (materialMoveVO.getBizType() == 20) {
					materialMoveVO.setOperationRecord("卸货");
				}
				if (materialMoveVO.getContainerType().intValue() != 0) {// 容器类型(0,仓储容器,1运输容器) 运输容器默认装车即触发
					BtPlanEntry planEntryByPlanIdAndSign = service.getPlanEntryByPlanIdAndSign(
							materialMoveVO.getPlanId(), UserContext.get().getCompanyId(), materialMoveVO.getSign() + 1);
					if (planEntryByPlanIdAndSign != null) {
						materialMoveVO.setAddressName("在从" + materialMoveVO.getAddressName() + "前往"
								+ planEntryByPlanIdAndSign.getAddressName() + "的途中");
					}
				}
				materialMoveVO.setOperationDateStr(myDateTimeFormat.format(materialMoveVO.getOperationDate()));
			}
			result.put("state", true);
			result.put("list", materialMoves);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 获取打尺信息
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping("/rule/{number}")
	@ResponseBody
	public JSONObject getRuleRecordInfo(@PathVariable String number) {
		JSONObject result = new JSONObject();
		int startRow = 0;
		if (!StringUtils.isEmpty(number)) {
			try {
				startRow = Integer.parseInt(number);
			} catch (NumberFormatException e) {
				e.printStackTrace();
				log.info("字符串转整形数字失败");
				result.put("state", false);
				result.put("msg", "系统错误");
				return result;
			}
		}
		List<BtRuleRecord> ruleRecords = service.queryRuleRecordByProjectId(UserContext.get().getCompanyId(), startRow);
		if (ruleRecords != null && ruleRecords.size() != 0) {
			for (BtRuleRecord btRuleRecord : ruleRecords) {
				btRuleRecord.setRuleDateStr(myDateTimeFormat.format(btRuleRecord.getRuleDate()));
				btRuleRecord.setVolume(
						btRuleRecord.getHeight().multiply(btRuleRecord.getLength()).multiply(btRuleRecord.getWidth())
								.divide(new BigDecimal("1000000")).setScale(6, BigDecimal.ROUND_HALF_UP));
			}
			result.put("state", true);
			result.put("list", ruleRecords);
		} else {
			result.put("state", true);
			result.put("list", null);
		}
		return result;
	}

	/**
	 * 查看异常
	 * 
	 * @param planId
	 * @return
	 */
	@RequestMapping("/exception/{planId}")
	@ResponseBody
	public JSONObject getException(@PathVariable String planId) {
		JSONObject result = new JSONObject();
		List<String> infolist = new ArrayList<String>();
		List<BtPlanEntry> planEntryException = service.getPlanEntryException(planId);
		if (!planEntryException.isEmpty() || planEntryException == null) {
			for (BtPlanEntry btPlanEntry : planEntryException) {
				if (btPlanEntry.getStates() == 1) {
					String enumTypeValue = btPlanEntry.getException();
					if (StringUtils.isEmpty(enumTypeValue)) {
						enumTypeValue = "未知";
					}
					String exceptionInfo = "在地点: " + btPlanEntry.getAddressName() + "  发生的异常信息为: " + enumTypeValue
							+ "。";
					infolist.add(exceptionInfo);
				}
			}
			result.put("state", true);
			result.put("data", infolist);
		} else {
			result.put("state", false);
			result.put("msg", "系统错误,请刷新页面再试");
		}
		return result;
	}

	// app下载
	@GetMapping("/download")
	public void downloadFile(String fileName, HttpServletResponse res) {
		InputStream fis = this.getClass().getResourceAsStream(fileName);
		if (fis == null) {
			try {
				res.setContentType("text/html;charset=utf-8");
				res.getWriter().write("模板资源不存在,请联系管理员!");
				res.flushBuffer();
			} catch (IOException e) {
			}
			return;
		}
		res.setContentType("application/octet-stream");
		try {
			res.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
		}
		try {
			IOUtils.copy(fis, res.getOutputStream());
			res.flushBuffer();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
				}
			}
		}
	}

}
